"use client";

import React, { useMemo } from "react";
import { cn } from "~/components/lib/utils";
import {
  Clock,
  Shield,
  AlertTriangle,
  CheckCircle,
  XCircle,
} from "lucide-react";
import {
  type VulnTableDataWithSources,
  type SourceAttribution,
} from "./VulnerabilityTableSourceColumns";

interface TimelineEvent {
  id: string;
  type: "discovery" | "confirmation" | "status_change";
  date: Date;
  source: string;
  source_version: string;
  vulnerability: VulnTableDataWithSources;
  confidence: number;
  status: string;
  notes?: string;
}

interface VulnerabilityTimelineProps {
  vulnerabilities: VulnTableDataWithSources[];
  className?: string;
  showConfidence?: boolean;
  groupBySource?: boolean;
  dateRange?: {
    start?: Date;
    end?: Date;
  };
}

export const VulnerabilityTimeline: React.FC<VulnerabilityTimelineProps> = ({
  vulnerabilities,
  className,
  showConfidence = true,
  groupBySource = false,
  dateRange,
}) => {
  // Generate timeline events from vulnerability data
  const timelineEvents = useMemo(() => {
    const events: TimelineEvent[] = [];

    vulnerabilities.forEach((vuln) => {
      if (!vuln.sources || vuln.sources.length === 0) return;

      vuln.sources.forEach((source) => {
        // Discovery event (first_seen)
        const discoveryDate = new Date(source.first_seen);
        if (
          !dateRange ||
          ((!dateRange.start || discoveryDate >= dateRange.start) &&
            (!dateRange.end || discoveryDate <= dateRange.end))
        ) {
          events.push({
            id: `${vuln.cve}-${source.source}-discovery`,
            type: "discovery",
            date: discoveryDate,
            source: source.source,
            source_version: source.source_version,
            vulnerability: vuln,
            confidence: source.confidence,
            status: source.status,
            notes: source.notes,
          });
        }

        // Confirmation event (last_seen, if different from first_seen)
        const confirmationDate = new Date(source.last_seen);
        if (confirmationDate.getTime() !== discoveryDate.getTime()) {
          if (
            !dateRange ||
            ((!dateRange.start || confirmationDate >= dateRange.start) &&
              (!dateRange.end || confirmationDate <= dateRange.end))
          ) {
            events.push({
              id: `${vuln.cve}-${source.source}-confirmation`,
              type: "confirmation",
              date: confirmationDate,
              source: source.source,
              source_version: source.source_version,
              vulnerability: vuln,
              confidence: source.confidence,
              status: source.status,
              notes: source.notes,
            });
          }
        }
      });
    });

    // Sort events by date
    return events.sort((a, b) => a.date.getTime() - b.date.getTime());
  }, [vulnerabilities, dateRange]);

  // Group events by date for better visualization
  const groupedEvents = useMemo(() => {
    const groups: Record<string, TimelineEvent[]> = {};

    timelineEvents.forEach((event) => {
      const dateKey = event.date.toDateString();
      if (!groups[dateKey]) {
        groups[dateKey] = [];
      }
      groups[dateKey].push(event);
    });

    return Object.entries(groups).map(([date, events]) => ({
      date: new Date(date),
      events: events.sort((a, b) => a.date.getTime() - b.date.getTime()),
    }));
  }, [timelineEvents]);

  const getSourceColor = (source: string) => {
    switch (source.toLowerCase()) {
      case "nmap":
        return "bg-blue-500 border-blue-600";
      case "agent":
        return "bg-green-500 border-green-600";
      case "rustscan":
        return "bg-orange-500 border-orange-600";
      case "manual":
        return "bg-purple-500 border-purple-600";
      case "naabu":
        return "bg-cyan-500 border-cyan-600";
      default:
        return "bg-gray-500 border-gray-600";
    }
  };

  const getSeverityColor = (severity: string) => {
    switch (severity) {
      case "CRITICAL":
        return "text-red-600 dark:text-red-400";
      case "HIGH":
        return "text-orange-600 dark:text-orange-400";
      case "MEDIUM":
        return "text-yellow-600 dark:text-yellow-400";
      case "LOW":
        return "text-green-600 dark:text-green-400";
      default:
        return "text-blue-600 dark:text-blue-400";
    }
  };

  const getEventIcon = (event: TimelineEvent) => {
    switch (event.type) {
      case "discovery":
        return <AlertTriangle className="h-4 w-4" />;
      case "confirmation":
        return <CheckCircle className="h-4 w-4" />;
      case "status_change":
        return <XCircle className="h-4 w-4" />;
      default:
        return <Clock className="h-4 w-4" />;
    }
  };

  const formatTime = (date: Date) => {
    return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
  };

  const formatDate = (date: Date) => {
    return date.toLocaleDateString([], {
      weekday: "short",
      month: "short",
      day: "numeric",
      year: "numeric",
    });
  };

  if (timelineEvents.length === 0) {
    return (
      <div
        className={cn(
          "flex items-center justify-center p-8 text-gray-500 dark:text-gray-400",
          className
        )}
      >
        <div className="text-center">
          <Clock className="mx-auto mb-2 h-8 w-8 opacity-50" />
          <p className="text-sm">
            No timeline events found for the selected criteria
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className={cn("space-y-6", className)}>
      {/* Timeline Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Clock className="h-5 w-5 text-gray-500" />
          <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
            Vulnerability Timeline
          </h3>
        </div>
        <div className="text-sm text-gray-500 dark:text-gray-400">
          {timelineEvents.length} events across {groupedEvents.length} days
        </div>
      </div>

      {/* Timeline */}
      <div className="relative">
        {/* Timeline line */}
        <div className="absolute bottom-0 left-8 top-0 w-0.5 bg-gray-200 dark:bg-gray-700"></div>

        {/* Timeline events */}
        <div className="space-y-6">
          {groupedEvents.map((group, groupIndex) => (
            <div key={group.date.toISOString()} className="relative">
              {/* Date marker */}
              <div className="mb-4 flex items-center gap-4">
                <div className="relative z-10 flex h-8 w-16 items-center justify-center rounded-full border border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-800">
                  <span className="text-xs font-medium text-gray-600 dark:text-gray-400">
                    {formatDate(group.date)}
                  </span>
                </div>
                <div className="h-px flex-1 bg-gray-200 dark:bg-gray-700"></div>
              </div>

              {/* Events for this date */}
              <div className="ml-16 space-y-3">
                {group.events.map((event, eventIndex) => (
                  <div
                    key={event.id}
                    className="relative flex items-start gap-4 rounded-lg border border-gray-200 bg-white p-4 shadow-sm transition-shadow hover:shadow-md dark:border-gray-700 dark:bg-gray-800"
                  >
                    {/* Event marker */}
                    <div
                      className={cn(
                        "absolute -left-12 top-4 flex h-8 w-8 items-center justify-center rounded-full border-2",
                        getSourceColor(event.source)
                      )}
                    >
                      <div className="text-white">{getEventIcon(event)}</div>
                    </div>

                    {/* Event content */}
                    <div className="min-w-0 flex-1">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <div className="mb-1 flex items-center gap-2">
                            <span className="font-mono text-sm font-medium text-gray-900 dark:text-gray-100">
                              {event.vulnerability.cve}
                            </span>
                            <span
                              className={cn(
                                "text-xs font-medium",
                                getSeverityColor(event.vulnerability.severity)
                              )}
                            >
                              {event.vulnerability.severity}
                            </span>
                            <span className="text-xs text-gray-500 dark:text-gray-400">
                              {formatTime(event.date)}
                            </span>
                          </div>

                          <p className="mb-2 line-clamp-2 text-sm text-gray-600 dark:text-gray-300">
                            {event.vulnerability.description}
                          </p>

                          <div className="flex items-center gap-4 text-xs text-gray-500 dark:text-gray-400">
                            <div className="flex items-center gap-1">
                              <span className="font-medium">Source:</span>
                              <span
                                className={cn(
                                  "rounded-full px-2 py-1 text-xs font-medium",
                                  event.source === "nmap"
                                    ? "bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-300"
                                    : event.source === "agent"
                                    ? "bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-300"
                                    : event.source === "rustscan"
                                    ? "bg-orange-100 text-orange-800 dark:bg-orange-900/20 dark:text-orange-300"
                                    : event.source === "manual"
                                    ? "bg-purple-100 text-purple-800 dark:bg-purple-900/20 dark:text-purple-300"
                                    : "bg-gray-100 text-gray-800 dark:bg-gray-900/20 dark:text-gray-300"
                                )}
                              >
                                {event.source} {event.source_version}
                              </span>
                            </div>

                            {showConfidence && (
                              <div className="flex items-center gap-1">
                                <Shield className="h-3 w-3" />
                                <span
                                  className={cn(
                                    "font-medium",
                                    event.confidence >= 0.9
                                      ? "text-green-600 dark:text-green-400"
                                      : event.confidence >= 0.7
                                      ? "text-yellow-600 dark:text-yellow-400"
                                      : "text-red-600 dark:text-red-400"
                                  )}
                                >
                                  {(event.confidence * 100).toFixed(0)}%
                                </span>
                              </div>
                            )}

                            <div className="flex items-center gap-1">
                              <span className="font-medium">Type:</span>
                              <span className="capitalize">
                                {event.type.replace("_", " ")}
                              </span>
                            </div>
                          </div>

                          {event.notes && (
                            <div className="mt-2 rounded bg-gray-50 p-2 text-xs text-gray-600 dark:bg-gray-700 dark:text-gray-300">
                              <span className="font-medium">Notes:</span>{" "}
                              {event.notes}
                            </div>
                          )}
                        </div>

                        {/* Risk score */}
                        <div className="ml-4 flex items-center gap-2">
                          <div className="text-right">
                            <div className="text-sm font-medium text-gray-900 dark:text-gray-100">
                              {event.vulnerability.riskScore.toFixed(1)}
                            </div>
                            <div className="text-xs text-gray-500 dark:text-gray-400">
                              CVSS
                            </div>
                          </div>
                          <div className="h-12 w-2 overflow-hidden rounded-full bg-gray-200 dark:bg-gray-700">
                            <div
                              className={cn(
                                "w-full rounded-full transition-all",
                                event.vulnerability.riskScore >= 9.0
                                  ? "bg-red-500"
                                  : event.vulnerability.riskScore >= 7.0
                                  ? "bg-orange-500"
                                  : event.vulnerability.riskScore >= 4.0
                                  ? "bg-yellow-500"
                                  : "bg-green-500"
                              )}
                              style={{
                                height: `${Math.min(
                                  event.vulnerability.riskScore * 10,
                                  100
                                )}%`,
                                marginTop: `${
                                  100 -
                                  Math.min(
                                    event.vulnerability.riskScore * 10,
                                    100
                                  )
                                }%`,
                              }}
                            ></div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Timeline Legend */}
      <div className="flex items-center justify-center gap-6 rounded-lg bg-gray-50 p-4 dark:bg-gray-900/50">
        <div className="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-400">
          <AlertTriangle className="h-3 w-3" />
          <span>Discovery</span>
        </div>
        <div className="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-400">
          <CheckCircle className="h-3 w-3" />
          <span>Confirmation</span>
        </div>
        <div className="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-400">
          <XCircle className="h-3 w-3" />
          <span>Status Change</span>
        </div>
      </div>
    </div>
  );
};

export default VulnerabilityTimeline;
